package com.rxyb.wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.rxyb.core.respone.R;
import com.rxyb.core.respone.enums.CommonCode;
import com.rxyb.redis.utils.RedisStringUtils;
import com.rxyb.toolize.VO;
import com.rxyb.wechat.constants.LocalConstants;
import com.rxyb.wechat.db.po.ThirdWechatCfg;
import com.rxyb.wechat.gateway.dto.tools.*;
import com.rxyb.wechat.service.ThirdWechatCfgService;
import com.rxyb.wechat.service.WechatToolsService;
import com.rxyb.wechat.utils.WechatToolsClient;
import com.rxyb.wechat.utils.bean.LocationResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商户信息 服务实现类
 * </p>
 *
 * @author DUYH
 * @since 2020-06-12
 */
@Slf4j
@Service
public class WechatToolsServiceImpl implements WechatToolsService {

    @Autowired(required = false)
    private RedisStringUtils redisStringUtils;
    @Autowired
    private WechatToolsClient wechatToolsClient;
    @Autowired(required = false)
    private ThirdWechatCfgService thirdWechatCfgService;

    @Override
    public R<GetLocationRsp> getLocation(GetLocationReq getLocationReq) {
        GetLocationRsp getLocationRsp = new GetLocationRsp();
        final LocationResult locat = wechatToolsClient.getLocat(getLocationReq.getAddr());
        if ("0".equals(locat.getStatus())) {
            return R.failed(CommonCode.FAILED);
        }
        final LocationResult.Result result = locat.getResult();
        getLocationRsp.setLng(result.getLocation().getLng());
        getLocationRsp.setLat(result.getLocation().getLat());
        getLocationRsp.setAdcode(result.getAd_info().getAdcode());
        getLocationRsp.setCity(result.getAddress_components().getCity());
        getLocationRsp.setDistrict(result.getAddress_components().getDistrict());
        getLocationRsp.setProvince(result.getAddress_components().getProvince());
        getLocationRsp.setStreet(result.getAddress_components().getStreet());
        getLocationRsp.setStreet_number(result.getAddress_components().getStreet_number());
        return R.ok(getLocationRsp);
    }

    @Override
    public R<GetDistanceRsp> getDistance(GetDistanceReq getDistanceReq) {
        GetDistanceRsp getDistanceRsp = new GetDistanceRsp();
        final String distance = wechatToolsClient.getDistance(getDistanceReq.getLng(), getDistanceReq.getLat(), getDistanceReq.getLng2(), getDistanceReq.getLat2());
        if (null == distance) {
            return R.failed(CommonCode.FAILED);
        }
        getDistanceRsp.setDistance(distance);
        return R.ok(getDistanceRsp);
    }

    @Override
    public Optional<String> getToken(String appId) {
        final Optional<String> s = redisStringUtils.get(LocalConstants.REDIS_GROUP_KEY_TOKEN, appId);
        if (s.isPresent()) {
            return s;
        }
        final ThirdWechatCfg query = thirdWechatCfgService.query(appId);
        if (null == query) {
            return Optional.empty();
        }
        final Optional<String> accessToken = wechatToolsClient.getAccessToken(query.getAppId(), query.getAppSecret());
        if (accessToken.isPresent()) {
            redisStringUtils.set(LocalConstants.REDIS_GROUP_KEY_TOKEN, appId, accessToken.get(), TimeUnit.MINUTES, LocalConstants.REDIS_TOKEN_TIMEOUT);
            return accessToken;
        }
        return Optional.empty();
    }

    @Override
    public R<SendWechatTemplateRsp> sendTemplate(SendWechatTemplateReq sendWechatTemplateReq) {
        //根据appId获取对应的TOKEN
        final Optional<String> token = getToken(sendWechatTemplateReq.getHostAppId());
        if (!token.isPresent()) {

        }
        //
        JSONObject map = new JSONObject();
        // 接收者opendid
        map.put("touser", sendWechatTemplateReq.getOpenId());
        // 模板Id
        map.put("template_id", sendWechatTemplateReq.getTemplateId());
        if (VO.isNotBlank(sendWechatTemplateReq.getAppid()) && VO.isNotBlank(sendWechatTemplateReq.getPagepath())) {
            // 跳小程序所需数据，不需跳小程序可不用传该数据
            JSONObject jsonApplet = new JSONObject();
            jsonApplet.put("appid", sendWechatTemplateReq.getAppid());
            jsonApplet.put("pagepath", sendWechatTemplateReq.getPagepath());
            map.put("miniprogram", jsonApplet);
        } else if (VO.isNotBlank(sendWechatTemplateReq.getUrl())) {
            map.put("url", sendWechatTemplateReq.getUrl());
        }

        // first 数据
        JSONObject jsonFirst = new JSONObject();
        jsonFirst.put("value", sendWechatTemplateReq.getFirst());
        // keyword1数据
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", sendWechatTemplateReq.getKeyword1());
        // keyword2 数据
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", sendWechatTemplateReq.getKeyword2());
        // keyword3 数据
        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", sendWechatTemplateReq.getKeyword3());
        // keyword3 数据
        JSONObject keyword4 = new JSONObject();
        keyword4.put("value", sendWechatTemplateReq.getKeyword4());
        // remark 数据
        JSONObject remark = new JSONObject();
        remark.put("value", sendWechatTemplateReq.getRemark());

        JSONObject jsonData = new JSONObject();
        jsonData.put("first", jsonFirst);
        if (VO.isNotBlank(sendWechatTemplateReq.getKeyword1())) {
            jsonData.put("keyword1", keyword1);
        }
        if (VO.isNotBlank(sendWechatTemplateReq.getKeyword2())) {
            jsonData.put("keyword2", keyword2);
        }
        if (VO.isNotBlank(sendWechatTemplateReq.getKeyword3())) {
            jsonData.put("keyword3", keyword3);
        }
        if (VO.isNotBlank(sendWechatTemplateReq.getKeyword4())) {
            jsonData.put("keyword4", keyword4);
        }
        if (VO.isNotBlank(sendWechatTemplateReq.getRemark())) {
            jsonData.put("remark", remark);
        }
        map.put("data", jsonData);
        String templateMessage = map.toJSONString();
        Optional<String> optional = wechatToolsClient.sendTemplate(token.get(), templateMessage);
        if (optional.isPresent()) {
            log.info("推送微信模板消息结果：【{}】==>【{}】", templateMessage, optional.get());
        } else {
            log.error("推送微信模板消息异常：【{}】", templateMessage);
        }

        return null;
    }
}
